package com.hisense.ovcloud.asop.config;

import io.r2dbc.spi.ConnectionFactories;
import io.r2dbc.spi.ConnectionFactory;
import io.r2dbc.spi.ConnectionFactoryOptions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;
import java.time.temporal.ChronoUnit;

@Configuration
@Slf4j
public class ClickhouseSourceConfig {
    private final ClickhouseProperties clickhouseProperties;

    public ClickhouseSourceConfig(ClickhouseProperties clickhouseProperties) {
        this.clickhouseProperties = clickhouseProperties;
    }

    @Bean
    public ConnectionFactory getClickhouseConnect() {
        log.info("begin to init clickhouse client");
        return ConnectionFactories.get(
                ConnectionFactoryOptions.builder()
                        .option(ConnectionFactoryOptions.DATABASE, Constants.ClickhouseConfigs.DEFAULT_DATABASE)
                        .option(ConnectionFactoryOptions.DRIVER, Constants.ClickhouseConfigs.DRIVER)
                        .option(ConnectionFactoryOptions.PASSWORD, clickhouseProperties.getPassword())
                        .option(ConnectionFactoryOptions.PROTOCOL, Constants.ClickhouseConfigs.DEFAULT_PROTOCOL)
                        .option(ConnectionFactoryOptions.USER, Constants.ClickhouseConfigs.DEFAULT_USER)

                        .option(ConnectionFactoryOptions.HOST, clickhouseProperties.getHost())
                        .option(ConnectionFactoryOptions.PORT, clickhouseProperties.getPort())
                        .option(ConnectionFactoryOptions.CONNECT_TIMEOUT, Duration.of(clickhouseProperties.getConnectTimeoutSeconds(), ChronoUnit.SECONDS))
                        .option(ConnectionFactoryOptions.STATEMENT_TIMEOUT, Duration.of(clickhouseProperties.getStatementTimeoutSeconds(), ChronoUnit.SECONDS))
                        .build()
        );
    }
}